<template>
  <div>
      <!--路径导航-->
       <el-breadcrumb separator-class="el-icon-arrow-right">
         <el-breadcrumb-item :to="{ path: '/users' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item>活动管理</el-breadcrumb-item>
         <el-breadcrumb-item>活动列表</el-breadcrumb-item>
         <el-breadcrumb-item>活动详情</el-breadcrumb-item>
       </el-breadcrumb>
       <!--搜索导航-->
       <el-card class="box-card" :body-style="{ padding: '10px'}">
          <el-row :gutter="15">
             <el-col :span="8"><div class="grid-content bg-purple">
                <el-input placeholder="请输入内容"  class="input-with-select" v-model='queryInfo.query' :clearable='true' @clear="getUsers">
                <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
                </el-input>   
             </div></el-col>
             <el-col :span="4"><div ><el-button type="primary" @click="addFormVisible=true">添加用户</el-button></div></el-col>
          </el-row>
          <!--用户信息表格-->
          <el-table :border='true' :data="userlist" >
             <el-table-column type="index" width="50"></el-table-column>
             <el-table-column prop="username" label="姓名" align='center'></el-table-column>
             <el-table-column prop="email" label="邮箱" align='center'></el-table-column>
             <el-table-column prop="mobile" label="电话" align='center'></el-table-column>
             <el-table-column prop="role_name" label="角色" align='center'></el-table-column>
             <el-table-column prop="mg_state" label="状态" align='center'>
                 <!--具名插槽  用scope.row 获取当前行-->
               <template slot-scope="scope">
                  <el-switch v-model="scope.row.mg_state" @change='changeStatus(scope.row)'></el-switch>
               </template>   
             </el-table-column>
             <el-table-column  label="操作" width='300'>
               <template slot-scope="scope">
                    <el-tooltip class="item" effect="light" content="分配角色" placement="top" :enterable='false'>
                        <el-button type="success" icon='el-icon-circle-plus' size='mini' @click="setRoleRight(scope.row)"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="light" content="修改用户" placement="top" :enterable='false' >
                        <el-button  type="warning" icon='el-icon-setting' size='mini' @click="editForm(scope.row.id)"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="light" content="删除用户" placement="top" :enterable='false' >
                        <el-button  type="danger" icon="el-icon-delete" size='mini' @click="open(scope.row.id)"></el-button>
                    </el-tooltip>
                </template>
             </el-table-column>
          </el-table>
          <!--分配用户角色-->
          <el-dialog title="提示" :visible.sync="setRoleRightVisible" >
             <div>
                <p>当前的用户: {{userInfo.username}}</p>
                <p>当前的角色: {{userInfo.role_name}}</p>
             </div>
                <span>修改当前用户角色</span>
               <el-select v-model="value" placeholder="请选择">
                 <el-option  v-for="item in roleList"  :key="item.id"  :label="item.roleName"  :value="item.id"> </el-option>
               </el-select>
             <span slot="footer" class="dialog-footer">
                 <el-button @click="setRoleRightVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRoleRightPut">确 定</el-button>
             </span>
             </el-dialog>
          <!--增加用户表单-->
         <el-dialog title="增加用户" :visible.sync="addFormVisible" @close='resetForm'>
            <el-form :model="addUserForm" label-width="80px" label-position='left' :rules="rules" ref="ruleForm">
               <el-form-item label="姓名" prop='username'>
                  <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
               </el-form-item>
               <el-form-item label="密码" prop='password'>
                  <el-input v-model="addUserForm.password" autocomplete="off"></el-input>
               </el-form-item>
               <el-form-item label="确认密码" prop='password2'>
                  <el-input v-model="addUserForm.password2" autocomplete="off"></el-input>
               </el-form-item>
               <el-form-item label="邮箱" prop='email'>
                  <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
               </el-form-item>
               <el-form-item label="电话" prop='mobile'>
                  <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
               </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
               <el-button @click="addFormVisible = false">取 消</el-button>
               <el-button type="primary" @click="adduser">确 定</el-button>
            </div>
         </el-dialog>
           <!--修改用户表单-->
           <el-dialog title="修改用户信息" :visible.sync="editFormVisible" @close='resetForm'>
            <el-form :model="editUserForm" label-width="80px" label-position='left' :rules="rules" ref="ruleForm2" hide-required-asterisk='false'>
               <el-form-item label="姓名" >
                  <el-input v-model="editUserForm.username" autocomplete="off" disabled></el-input>
               </el-form-item>
               <el-form-item label="邮箱" prop='email' >
                  <el-input v-model="editUserForm.email" autocomplete="off"></el-input>
               </el-form-item>
               <el-form-item label="电话" prop='mobile' >
                  <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
               </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
               <el-button @click="editFormVisible = false">取 消</el-button>
               <el-button type="primary" @click="edituser">确 定</el-button>
            </div>
           </el-dialog>
          <!--页码导航-->
          <div class="block">
               <el-pagination
               @size-change="handleSizeChange"  
               @current-change="handleCurrentChange"
               :current-page="queryInfo.pagenum"
               :page-sizes="[1,2,3,6,10]"
               :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
               :total="total">
               </el-pagination>
             </div>
       </el-card> 
  </div> 
</template>
<script>
export default {
    //挂在生命周期钩子函数
    created(){
        this.getUsers()
    },
    data(){
        var checPassword = (rule, value, callback) => {
             
            }
        var checPassword2 = (rule, value, callback) => {
            if (value === '') {
               callback(new Error('请再次输入密码'));
            } else if (value !== this.addUserForm.password) {
               callback(new Error('两次输入密码不一致!'));
            } else {
              callback();
            }
        }
        var checkMobile = (rule, value, callback) => {
             var reg=/^1(3|4|5|6|7|8|9)\d{9}$/
             if(reg.test(value)){
                callback()
             }else{
                 callback('输入手机号有误')
             }
            }
        return{
            //分配用户角色
            setRoleRightVisible:false,
            roleList:'',
            value:'',
            userInfo:'',
            //添加用户信息
            addUserForm:{
                username:'',
                password:'',
                password2:'',
                email:'',
                mobile:''
            },
            //添加用户校验规则
            rules:{
                username: [
                 { required: true, message: '请输入用户名', trigger: 'blur' },
                 { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                 { required: true, message: '请输入密码', trigger: 'blur' },
                 { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                password2: [
                 { required: true, message: '请再次输入密码', trigger: 'blur' },
                 { validator: checPassword2, trigger: 'blur' }
                ],
                email: [
                 { required: true, message: '请输入邮箱', trigger: 'blur' },
                 { type: 'email', message: '请正确输入邮箱', trigger: 'blur' }
                ],
                mobile: [
                 { required: true, message: '请输入手机号', trigger: 'blur' },
                 { validator:checkMobile, message: '请正确输入手机号', trigger: 'blur' }
                ],
            },
            //修改用户信息
            editUserForm:[],
            addFormVisible:false,
            editFormVisible:false,
            //设置查找请求的数据
            queryInfo:{
                query:'',//查询条件
                pagenum:1,//第几页
                pagesize:2//每页显示的条数
            },
            //用户列表数据
            userlist:[],
            value1:true,
            total:0,
            //删除用户
            deleteVisible:false
        }
    },
    methods:{
        //发送带参数get请求 要用params   
        async getUsers(){
            const {data:res}=await this.$http.get('users',{params:this.queryInfo})
            if(res.meta.status!=200) return this.$message.error('请求数据错误')
            console.log(res);
            this.userlist=res.data.users
            this.total=res.data.total
        },
        //监听用户状态 改变状态  发送put请求 修改数据库信息 
        async changeStatus(userinfo){
            const {data:res}=await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status!=200){
               userinfo.mg_state=!userinfo.mg_state
               return this.$message.error('状态改变失败')
            } 
            this.$message.success('修改状态成功')
        },
        //修改每页显示条数
        handleSizeChange(val){
           this.queryInfo.pagesize=val;
           this.getUsers()
        },
        //显示当前页数的信息
        handleCurrentChange(val){
           this.queryInfo.pagenum=val
           this.getUsers();
        },
        //重置表单
        resetForm(){
           this.$refs.ruleForm.resetFields()
        },
        //添加用户预验证
        adduser(){
           this.$refs.ruleForm.validate(async (valid) => { 
              if (!valid) return
              // 发请求
              const { data: res } = await this.$http.post('users', this.addUserForm)
             if (res.meta.status !== 201) {
                 return this.$message({
                 message: '添加用户失败',
                 type: 'error'
                })
             }
            this.$message.success('添加成功')
            this.addFormVisible=false
            this.getUsers()
            })
        },
        //分配用户角色
        async setRoleRight(user){
            this.userInfo=user
            const {data:res}=await this.$http.get('roles')
            if(res.meta.status!=200) return thid.$message.error('请求数据失败')
            this.roleList=res.data
            this.setRoleRightVisible=true
        },
        async setRoleRightPut(){
            const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.value})
            if(res.meta.status!=200) return this.$message.error('修改数据失败')
            this.getUsers()
            this.value=''
            this.setRoleRightVisible=false
        },
        //获取要修改用户的信息
        async editForm(id){
            this.editFormVisible=true
            const {data:res}=await this.$http.get(`users/${id}`)
            if(res.meta.status!=200) return this.$message.error('数据获取失败')
            this.editUserForm=res.data
            },
        //修改用户信息请求
        edituser(){
            this.$refs.ruleForm2.validate(async (valid) => { 
              if (!valid) return
              // 发请求
              const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`,{
                  email:this.editUserForm.email,
                  mobile:this.editUserForm.mobile
              })
             if (res.meta.status !== 200) return this.$message.error('修改用户失败')
                this.$message.success('修改用户信息成功')
                this.editFormVisible=false
                this.$refs.ruleForm2.resetFields()
                this.getUsers()
            })
        },
        //删除用户
        async open(id) {
           const result=await this.$confirm('你将要删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch((err) =>err )
           if(result=='confirm'){
              const {data:res}=await this.$http.delete(`users/${id}`)
              if(res.meta.status!=200) return this.$message.error('删除用户失败')
              this.$message.success('删除用户成功')
              this.queryInfo.pagenum=Math.floor(this.total/this.queryInfo.pagesize)
              this.getUsers()
           }
      }
    }
 }

</script>
<style lang="less" scoped>
  .el-breadcrumb{
      margin-bottom:15px
  }
  .el-table{
      margin-top: 10px;
      margin-bottom: 10px;
  }
</style>